package cn.sfrog.project.biz.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.sfrog.common.constant.ConfigConstants;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.core.domain.model.LoginUser;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.enums.UserTypeEnum;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.common.utils.bean.BeanUtils;
import cn.sfrog.framework.web.service.TokenService;
import cn.sfrog.project.biz.admin.domain.*;
import cn.sfrog.project.biz.admin.domain.vo.*;
import cn.sfrog.project.biz.admin.enums.BizOrderStatusEnum;
import cn.sfrog.project.biz.admin.enums.BizUserTradeTypeEnum;
import cn.sfrog.project.biz.admin.mapper.*;
import cn.sfrog.project.biz.admin.service.IBizServiceOrderDataUploadService;
import cn.sfrog.project.biz.admin.service.IBizServiceOrderService;
import cn.sfrog.project.biz.admin.service.IBizUserTradeRecordService;
import cn.sfrog.project.biz.web.mapstruct.AppServiceOrderConverter;
import cn.sfrog.project.biz.web.vo.order.*;
import cn.sfrog.project.biz.web.vo.websocket.AppKfUserVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import cn.sfrog.system.mapper.SysUserMapper;
import cn.sfrog.system.service.ISysConfigService;
import cn.sfrog.system.service.ISysDictDataService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;


/**
 * 服务订单Service业务层处理
 */
@Service
@Slf4j
public class BizServiceOrderServiceImpl extends ServiceImpl<BizServiceOrderMapper, BizServiceOrder> implements IBizServiceOrderService {
    @Resource
    private BizServiceOrderMapper bizServiceOrderMapper;
    @Resource
    private BizServiceOrderEvaluationMapper bizServiceOrderEvaluationMapper;
    @Resource
    private BizServiceOrderComplaintMapper bizServiceOrderComplaintMapper;
    @Resource
    private BizServiceMapper bizServiceMapper;
    @Resource
    private BizComboMapper bizComboMapper;
    @Resource
    private RedisCache redisCache;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private TokenService tokenService;
    @Resource
    private IBizUserTradeRecordService bizUserTradeRecordService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private IBizServiceOrderDataUploadService bizServiceOrderDataUploadService;
    @Resource
    private BizUserAccountMapper bizUserAccountMapper;
    @Resource
    private BizUserCommissionMapper bizUserCommissionMapper;
    @Resource
    private BizMessageConversationMapper bizMessageConversationMapper;

    /**
     * 查询服务订单
     *
     * @param id 服务订单主键
     * @return 服务订单
     */
    @Override
    public BizServiceOrderVO selectBizServiceOrderById(Long id) {
        BizServiceOrderVO bizServiceOrderVO = bizServiceOrderMapper.selectBizServiceOrderById(id);
        //查询服务或者套餐的信息
        if (BizServiceOrder.BUY_TYPE_SERVICE.equals(bizServiceOrderVO.getBuyType())) {
            //服务
            BizServiceInfoResultVO resultVO = bizServiceMapper.selectServiceInfoById(bizServiceOrderVO.getProductId());
            bizServiceOrderVO.setServiceInfoVo(resultVO);
        } else if (BizServiceOrder.BUY_TYPE_COMBO.equals(bizServiceOrderVO.getBuyType())) {
            //套餐
            BizComboInfoResultVO resultVO = bizComboMapper.selectComboInfoById(bizServiceOrderVO.getProductId());
            String[] serviceIds = resultVO.getServiceIds().split(",");
            List<BizService> bizServices = BizService.DAO.selectList(Wrappers.lambdaQuery(BizService.class).in(BizService::getId, (Object[]) serviceIds));
            List<BizServiceInfoResultVO> bizServiceInfoResultVOS = BeanUtils.convertList2List(bizServices, BizServiceInfoResultVO.class);
            resultVO.setServiceInfoResultVOList(bizServiceInfoResultVOS);
            bizServiceOrderVO.setComboInfoResultVo(resultVO);
        }


        //查询订单评价信息
        BizServiceOrderEvaluationQueryVO evaluationQueryVO = new BizServiceOrderEvaluationQueryVO();
        evaluationQueryVO.setServiceOrderSn(bizServiceOrderVO.getServiceOrderSn());
        List<BizServiceOrderEvaluationVO> bizServiceOrderEvaluationVOS = bizServiceOrderEvaluationMapper.selectBizServiceOrderEvaluationList(evaluationQueryVO);
        if (CollectionUtil.isNotEmpty(bizServiceOrderEvaluationVOS)) {
            bizServiceOrderVO.setOrderEvaluation(bizServiceOrderEvaluationVOS.get(0));
        } else {
            bizServiceOrderVO.setOrderEvaluation(new BizServiceOrderEvaluationVO());
        }
        //查询订单投诉信息
        BizServiceOrderComplaintQueryVO complaintQueryVO = new BizServiceOrderComplaintQueryVO();
        complaintQueryVO.setServiceOrderSn(bizServiceOrderVO.getServiceOrderSn());
        List<BizServiceOrderComplaintVO> bizServiceOrderComplaintVOS = bizServiceOrderComplaintMapper.selectBizServiceOrderComplaintList(complaintQueryVO);
        if (CollectionUtil.isNotEmpty(bizServiceOrderComplaintVOS)) {
            bizServiceOrderVO.setOrderComplaint(bizServiceOrderComplaintVOS.get(0));
        } else {
            bizServiceOrderVO.setOrderComplaint(new BizServiceOrderComplaintVO());
        }
        return bizServiceOrderVO;
    }

    /**
     * 查询服务订单列表
     *
     * @param query 服务订单
     * @return 服务订单
     */
    @Override
    public List<BizServiceOrderVO> selectBizServiceOrderList(BizServiceOrderQueryVO query) {
        if (query.getDateValue() != null) {
            query.setStartTime(query.getDateValue()[0] + " 00:00:00");
            query.setEndTime(query.getDateValue()[1] + " 23:59:59");
        }
        return bizServiceOrderMapper.selectBizServiceOrderList(query);
    }

    @Override
    public List<BizServiceOrderVO> selectBizServiceOrderDispatchList(BizServiceOrderQueryVO queryVO) {
        if (queryVO.getDateValue() != null) {
            queryVO.setStartTime(queryVO.getDateValue()[0] + " 00:00:00");
            queryVO.setEndTime(queryVO.getDateValue()[1] + " 23:59:59");
        }
        return bizServiceOrderMapper.selectBizServiceOrderDispatchList(queryVO);
    }

    /**
     * 新增服务订单
     *
     * @param form 服务订单
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizServiceOrder(BizServiceOrderFormVO form) {
        BizServiceOrder bizServiceOrder = new BizServiceOrder();
        BeanUtils.copyProperties(form, bizServiceOrder);
        bizServiceOrder.setCreateTime(new Date());
        bizServiceOrder.setCreateBy(SecurityUtils.getUsername());
        bizServiceOrder.setUpdateTime(new Date());
        bizServiceOrder.setUpdateBy(SecurityUtils.getUsername());
        return bizServiceOrder.insert();
    }

    /**
     * 修改服务订单
     *
     * @param form 服务订单
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizServiceOrder(BizServiceOrderFormVO form) {
        BizServiceOrder bizServiceOrder = new BizServiceOrder();
        BeanUtils.copyProperties(form, bizServiceOrder);
        bizServiceOrder.setUpdateTime(new Date());
        bizServiceOrder.setUpdateBy(SecurityUtils.getUsername());
        return bizServiceOrder.updateById();
    }

    /**
     * 批量删除服务订单
     *
     * @param ids 需要删除的服务订单主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizServiceOrderByIds(Long[] ids) {
        return BizServiceOrder.DAO.delete(Wrappers.lambdaQuery(BizServiceOrder.class).in(BizServiceOrder::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
//        return BizServiceOrder.DAO.update(Wrappers.lambdaUpdate(BizServiceOrder.class).in(BizServiceOrder::getId, (Object[]) vo.getIds()).set(BizServiceOrder::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int cancel(Long id) {
        BizServiceOrder serviceOrder = BizServiceOrder.DAO.selectById(id);
        BizServiceOrder bizServiceOrder = new BizServiceOrder();
        bizServiceOrder.setId(id);
        bizServiceOrder.setOrderStatus(BizOrderStatusEnum.CANCELLED.getCode());
        bizServiceOrder.setCancelTime(DateUtils.getNowDate());
        bizServiceOrder.setUpdateBy(SecurityUtils.getUsername());
        bizServiceOrder.setUpdateTime(DateUtils.getNowDate());
        boolean flag = bizServiceOrder.updateById();
        if(flag){
            if(BizOrderStatusEnum.PENDING_ORDER.getCode().equals(serviceOrder.getOrderStatus())){
                //取消订单时要把订单金额退回到用户原来账户里面
                LambdaQueryWrapper<BizUserAccount> queryWrapper = new LambdaQueryWrapper<BizUserAccount>()
                        .eq(BizUserAccount::getUserId,serviceOrder.getUserId());
                BizUserAccount bizUserAccount = BizUserAccount.DAO.selectOne(queryWrapper);
                if(StringUtils.isNotNull(bizUserAccount)){
                    bizUserAccount.setAccountBalance(bizUserAccount.getAccountBalance().add(serviceOrder.getAmount()));
                    bizUserAccount.updateById();
                }
                SysUser sysUser = new SysUser();
                sysUser.setUserId(serviceOrder.getUserId());
                sysUser.setEscortBeanCount(bizUserAccount.getAccountBalance().add(bizUserAccount.getGiveAwayAmount()).add(bizUserAccount.getCommissionAmount()));
                sysUserMapper.updateUser(sysUser);
                //取消订单记录交易明细
                String nameStr = "";
                if (BizServiceOrder.BUY_TYPE_SERVICE.equals(serviceOrder.getBuyType())) {
                    //购买的是服务
                    BizService bizService = BizService.DAO.selectById(serviceOrder.getProductId());
                    nameStr = bizService.getName();
                } else if (BizServiceOrder.BUY_TYPE_COMBO.equals(serviceOrder.getBuyType())) {
                    //购买的是套餐
                    BizCombo bizCombo = BizCombo.DAO.selectById(serviceOrder.getProductId());
                    nameStr = bizCombo.getComboName();
                }

                //记录交易记录
                bizUserTradeRecordService.saveUserTradeRecord(serviceOrder.getUserId(), serviceOrder.getAmount(), BizUserTradeTypeEnum.ORDER_CANCEL.getCode(),
                        bizServiceOrder.getServiceOrderSn(), "订单取消("+nameStr+")");
            }

        }
        return flag ? 1 : 0;
    }

    @Override
    public int dispatch(BizServiceOrderDispatchFormVO formVO) {
        System.out.println(":::::::" + JSONObject.toJSONString(formVO));
        BizServiceOrder bizServiceOrder = BizServiceOrder.DAO.selectById(formVO.getId());
        bizServiceOrder.setAcceptUserId(formVO.getAcceptUserId());
        bizServiceOrder.setDispatchTime(DateUtils.getNowDate());
        bizServiceOrder.setAcceptExpireTime(DateUtils.addMinutes(DateUtils.getNowDate(), 30));
//        if (UserTypeEnum.MEMBER.getCode().equals(formVO.getDispatchType())) {
//            //如果是派单给会员 此时该订单应是待支付的订单且是客服帮下单的
//            if (BizOrderStatusEnum.PENDING_SERVICE.getCode().equals(bizServiceOrder.getOrderStatus())) {
//                bizServiceOrder.setOrderStatus(BizOrderStatusEnum.PENDING_PAY.getCode());
//            } else {
//                throw new ServiceException("只有待服务的订单才可以派单给会员");
//            }
//        } else {
//
//        }

        bizServiceOrder.setOrderStatus(BizOrderStatusEnum.PENDING_ORDER.getCode());
        return bizServiceOrder.updateById() ? 1 : 0;
    }

    @Override
    public AppServiceOrderVO submitServiceOrder(AppServiceOrderFormVO formVO) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        BizService bizService = new BizService();
        BizCombo bizCombo = new BizCombo();
        BizServiceOrder bizServiceOrder = AppServiceOrderConverter.INSTANCE.formTo(formVO);

        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH");
        String formattedDate = outputFormat.format(formVO.getAppointmentDate());
        String[] s = formattedDate.split(" ");
        /**
         * 当天5点-10点 订单金额为1.2倍
         * 10点-8点 1.5倍
         */
        double amount = Integer.valueOf(formVO.getAmount().toString()) *1.0;
        if (Integer.valueOf(s[1])>22){
            //  1.5倍
             amount = Integer.valueOf(formVO.getAmount().toString()) * 1.5;
//            System.out.println("1.5倍");
        }
        if (Integer.valueOf(s[1])<8){
            //  1.5倍
//            System.out.println("1.5倍");
            amount = Integer.valueOf(formVO.getAmount().toString()) * 1.5;
        }
        if (Integer.valueOf(s[1])<23 && 17<Integer.valueOf(s[1])){
            // 1.2倍
//            System.out.println("1.2倍");
            amount = Integer.valueOf(formVO.getAmount().toString()) * 1.2;
        }
        bizServiceOrder.setAmount(BigDecimal.valueOf(amount));
        bizServiceOrder.setUserId(user.getUserId());
        bizServiceOrder.setType(BizServiceOrder.TYPE_USER);
        bizServiceOrder.setServiceOrderSn(redisCache.buildServiceOrderSn());
        bizServiceOrder.setOrderStatus(BizOrderStatusEnum.PENDING_PAY.getCode());
        bizServiceOrder.setIdCardNumber(formVO.getIdCardNumber());
        bizServiceOrder.setAddress(formVO.getAddress());
        bizServiceOrder.setRegistrationType(formVO.getRegistrationType());
        bizServiceOrder.setDrugType(formVO.getDrugType());
        bizServiceOrder.setDepartmentId(formVO.getDepartmentId());
        bizServiceOrder.setDoctorId(formVO.getDoctorId());
        System.out.println("传参：：：："+JSONObject.toJSONString(formVO));
        System.out.println("接单陪护id：：：："+bizServiceOrder.getAcceptUserId());
        if (BizServiceOrder.BUY_TYPE_SERVICE.equals(formVO.getBuyType())) {
            //购买的是服务
             bizService = BizService.DAO.selectById(formVO.getProductId());

             String type = bizService.getType();
             if(BizService.TYPE_PZ.equals(type)){
                 bizServiceOrder.setDispatchType("陪诊");
             }else if(BizService.TYPE_HL.equals(type)){
                 bizServiceOrder.setDispatchType("护理");
             }else if(BizService.TYPE_WZ.equals(type)){
                 bizServiceOrder.setDispatchType("问诊");
             }else {
                 bizServiceOrder.setDispatchType(bizService.getName());
             }
        }else if(BizServiceOrder.BUY_TYPE_COMBO.equals(formVO.getBuyType())){
            //购买的是套餐
            bizCombo = BizCombo.DAO.selectById(formVO.getProductId());
            String[] serviceIds = bizCombo.getServiceIds().split(",");
            String serviceTypeName = bizServiceMapper.selectServiceTypeName(serviceIds);
            if(StringUtils.isNotBlank(serviceTypeName)){
                bizServiceOrder.setDispatchType(serviceTypeName);
            }
        }
        //生成的订单 30分钟后过期
        bizServiceOrder.setPaymentExpireTime(DateUtils.addMinutes(DateUtils.getNowDate(),30));
        bizServiceOrder.setCreateTime(DateUtils.getNowDate());
        bizServiceOrder.setCreateBy(user.getUserName());
        bizServiceOrder.setUpdateTime(DateUtils.getNowDate());
        bizServiceOrder.setUpdateBy(user.getUserName());
        bizServiceOrder.insert();
        AppServiceOrderVO result = AppServiceOrderConverter.INSTANCE.entity2Entity(bizServiceOrder);
        if (StringUtils.isNotNull(result)) {
            //查询医院信息
            BizHospital hospital = BizHospital.DAO.selectById(result.getHospitalId());
            result.setDoctorId(formVO.getDoctorId());
            result.setDepartmentId(formVO.getDepartmentId());
            result.setHospitalName(hospital.getName());
            result.setProvince(hospital.getProvince());
            result.setCity(hospital.getCity());
            result.setDistinct(hospital.getDistrict());
            result.setAddress(hospital.getAddress());
            result.setLatitude(hospital.getLatitude());
            result.setLongitude(hospital.getLongitude());
            result.setUserAddress(formVO.getAddress());
            result.setDrugType(formVO.getDrugType());
            result.setRegistrationType(formVO.getRegistrationType());
            if (BizServiceOrder.BUY_TYPE_SERVICE.equals(formVO.getBuyType())) {
                result.setServiceName(bizService.getName());
                result.setServiceImage(bizService.getImage());
                result.setServicePrice(bizService.getPrice());
            } else if (BizServiceOrder.BUY_TYPE_COMBO.equals(formVO.getBuyType())) {
                result.setServiceName(bizCombo.getComboName());
                result.setServiceImage(bizCombo.getComboImage());
                result.setServicePrice(bizCombo.getPrice());
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean createHelpCustomerOrder(BizHelpCustomerOrderFormVO form) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        BizService bizService = new BizService();
        BizCombo bizCombo = new BizCombo();
        BizServiceOrder serviceOrder = AppServiceOrderConverter.INSTANCE.helpCustomerForm2Entity(form);
        serviceOrder.setType(BizServiceOrder.TYPE_KF);
        serviceOrder.setServiceOrderSn(redisCache.buildServiceOrderSn());
        serviceOrder.setOrderStatus(BizOrderStatusEnum.PENDING_PAY.getCode());
        serviceOrder.setKfId(user.getUserId());
        if (BizServiceOrder.BUY_TYPE_SERVICE.equals(form.getBuyType())) {
            //购买的是服务
            bizService = BizService.DAO.selectById(form.getProductId());
            String type = bizService.getType();
            if(BizService.TYPE_PZ.equals(type)){
                serviceOrder.setDispatchType("陪诊");
            }else if(BizService.TYPE_HL.equals(type)){
                serviceOrder.setDispatchType("护理");
            }else if(BizService.TYPE_WZ.equals(type)){
                serviceOrder.setDispatchType("问诊");
            }
        }else if(BizServiceOrder.BUY_TYPE_COMBO.equals(form.getBuyType())){
            //购买的是套餐
            bizCombo = BizCombo.DAO.selectById(form.getProductId());
            String[] serviceIds = bizCombo.getServiceIds().split(",");
            String serviceTypeName = bizServiceMapper.selectServiceTypeName(serviceIds);
            if(StringUtils.isNotBlank(serviceTypeName)){
                serviceOrder.setDispatchType(serviceTypeName);
            }
        }
        serviceOrder.setCreateTime(DateUtils.getNowDate());
        serviceOrder.setCreateBy(user.getUserName());
        serviceOrder.setUpdateTime(DateUtils.getNowDate());
        serviceOrder.setUpdateBy(user.getUserName());
        serviceOrder.setPaymentExpireTime(DateUtils.addMinutes(DateUtils.getNowDate(), 30));
        serviceOrder.setAcceptExpireTime(DateUtils.addMinutes(DateUtils.getNowDate(), 30));
        return serviceOrder.insert();
    }

    @Override
    public AppServiceOrderVO getServiceOrderByOrderNum(String orderNum) {
        return bizServiceOrderMapper.getServiceOrderByOrderNum(orderNum);
    }

    @Override
    public void updateServiceOrderByOrderNum(HashMap orderNum) {
        bizServiceOrderMapper.updateServiceOrderByOrderNum(orderNum);
    }

    @Override
    public List<AppServiceOrderResultVO> selectAppServiceOrderList(AppServiceOrderQueryVO query) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUser sysUser = sysUserMapper.selectUserById(user.getUserId());
        query.setUserId(user.getUserId());
        query.setUserType(sysUser.getUserType());
        return bizServiceOrderMapper.selectAppServiceOrderList(query);
    }

    @Override
    public AppServiceOrderVO selectAppServiceOrderDetail(Long id) {
        BizServiceOrder bizServiceOrder = BizServiceOrder.DAO.selectById(id);
        AppServiceOrderVO result = AppServiceOrderConverter.INSTANCE.entity2Entity(bizServiceOrder);
        if (StringUtils.isNotNull(result)) {
            //查询医院信息
            BizHospital hospital = BizHospital.DAO.selectById(result.getHospitalId());
            result.setHospitalName(hospital.getName());
            result.setProvince(hospital.getProvince());
            result.setCity(hospital.getCity());
            result.setDistinct(hospital.getDistrict());
            result.setAddress(hospital.getAddress());
            result.setLongitude(hospital.getLongitude());
            result.setLatitude(hospital.getLatitude());
            if (BizServiceOrder.BUY_TYPE_SERVICE.equals(bizServiceOrder.getBuyType())) {
                BizService bizService = BizService.DAO.selectById(bizServiceOrder.getProductId());
                result.setServiceName(bizService.getName());
                result.setServiceImage(bizService.getImage());
                result.setServicePrice(bizService.getPrice());
//                String serviceTypeName = sysDictDataService.selectDictLabel("biz_service_type", bizService.getType());
//                if(StringUtils.isNotBlank(serviceTypeName)){
//                    result.setServiceTypeName(serviceTypeName);
//                }
            } else if (BizServiceOrder.BUY_TYPE_COMBO.equals(bizServiceOrder.getBuyType())) {
                BizCombo bizCombo = BizCombo.DAO.selectById(bizServiceOrder.getProductId());
                result.setServiceName(bizCombo.getComboName());
                result.setServiceImage(bizCombo.getComboImage());
                result.setServicePrice(bizCombo.getPrice());

//                String[] serviceIds = bizCombo.getServiceIds().split(",");
//                String serviceTypeName = bizServiceMapper.selectServiceTypeName(serviceIds);
//                if(StringUtils.isNotBlank(serviceTypeName)){
//                    result.setServiceTypeName(serviceTypeName);
//                }
            }
            //查询资料上传列表
            List<AppOrderDataUploadResultVO> dataUploadList = bizServiceOrderDataUploadService.selectDataUploadListByOrder(id);
            result.setDataUploadList(dataUploadList);
            if(result.getAcceptUserId() !=null){
                SysUser sysUser = sysUserMapper.selectUserById(result.getAcceptUserId());
                if(sysUser != null){
                    result.setAcceptUserName(sysUser.getNickName());
                    result.setAcceptUserAvatar(sysUser.getAvatar());
                }
            }
            if(result.getUserId() != null){
                SysUser sysUser = sysUserMapper.selectUserById(result.getUserId());
                if(sysUser != null){
                    result.setUserName(sysUser.getNickName());
                    result.setUserAvatar(sysUser.getAvatar());
                }
            }
        }
        result.setServiceTypeName(bizServiceOrder.getDispatchType());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean payment(Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        BizServiceOrder bizServiceOrder = BizServiceOrder.DAO.selectById(id);
        if (!BizOrderStatusEnum.PENDING_PAY.getCode().equals(bizServiceOrder.getOrderStatus())) {
            throw new ApiException("此订单状态不可进行支付");
        }
        BizService bizService = new BizService();
        BizCombo bizCombo = new BizCombo();
        Boolean flag = false;
        LambdaQueryWrapper<BizUserAccount> lambdaQueryWrapper = new LambdaQueryWrapper<BizUserAccount>()
                .eq(BizUserAccount::getUserId, user.getUserId());
        BizUserAccount bizUserAccount = BizUserAccount.DAO.selectOne(lambdaQueryWrapper);
        //账户可用余额
        BigDecimal ableAmount = bizUserAccount.getAccountBalance();
        //赠送金额
        BigDecimal giveAwayAmount = bizUserAccount.getGiveAwayAmount();
        //可用的代理提成金额
        BigDecimal commissionAmount = bizUserAccount.getCommissionAmount().subtract(bizUserAccount.getFreezeAmount());

        //订单金额
        BigDecimal orderAmount = bizServiceOrder.getAmount();
        if (orderAmount.compareTo(ableAmount.add(giveAwayAmount).add(commissionAmount)) == 1) {
            throw new ApiException("账户可用余额不足,请先进行充值!");
        }
        //变成待接单
        bizServiceOrder.setOrderStatus(BizOrderStatusEnum.PENDING_ORDER.getCode());
        bizServiceOrder.setAcceptExpireTime(DateUtils.addMinutes(DateUtils.getNowDate(),30));
        if (BizServiceOrder.BUY_TYPE_SERVICE.equals(bizServiceOrder.getBuyType())) {
            //购买的是服务
            bizService = BizService.DAO.selectById(bizServiceOrder.getProductId());
            flag = true;
        } else if (BizServiceOrder.BUY_TYPE_COMBO.equals(bizServiceOrder.getBuyType())) {
            //购买的是套餐
            bizCombo = BizCombo.DAO.selectById(bizServiceOrder.getProductId());
        }
        //计算接单人预计收入金额
        String orderCommission = sysConfigService.selectConfigByKey(ConfigConstants.ORDER_COMMISSION_SCALE);
        BigDecimal divide = new BigDecimal(orderCommission).divide(BigDecimal.valueOf(100));
        BigDecimal giveAmount = orderAmount.subtract(orderAmount.multiply(divide));

        bizServiceOrder.setExpectIncomeAmount(giveAmount.setScale(0,BigDecimal.ROUND_UP));
        bizServiceOrder.setPaymentTime(DateUtils.getNowDate());
        bizServiceOrder.setUpdateTime(DateUtils.getNowDate());
        bizServiceOrder.setUpdateBy(user.getUserName());
        boolean update = bizServiceOrder.updateById();
        if (update) {
            //更新用户账户信息
            // 1.如果支付金额 < 账户可用余额  则直接扣减账户余额
            if (orderAmount.compareTo(ableAmount) < 1) {
                bizUserAccount.setAccountBalance(bizUserAccount.getAccountBalance().subtract(orderAmount));
            }else if((orderAmount.compareTo(ableAmount) == 1) && (orderAmount.compareTo((ableAmount.add(commissionAmount)))) < 1 ) {
                //2.（支付金额 > 账户可用余额） 并且 （支付金额 < 账户可用余额 + 代理提成金额）
                bizUserAccount.setAccountBalance(bizUserAccount.getAccountBalance().subtract(ableAmount));
                BigDecimal subGiveAwayAmount = orderAmount.subtract(ableAmount);
                bizUserAccount.setCommissionAmount(bizUserAccount.getCommissionAmount().subtract(subGiveAwayAmount));
               // bizUserAccount.setGiveAwayAmount(bizUserAccount.getGiveAwayAmount().subtract(subGiveAwayAmount));
            }else {
                // 3.（支付金额 > 账户可用余额） && （支付金额 > 账户可用余额 + 代理分成金额） && （支付金额 < 账户可用余额 + 代理分成金额 + 充值赠送金额）
                bizUserAccount.setAccountBalance(bizUserAccount.getAccountBalance().subtract(ableAmount));
                bizUserAccount.setCommissionAmount(bizUserAccount.getCommissionAmount().subtract(commissionAmount));
                BigDecimal subGiveAwayAmount = orderAmount.subtract(ableAmount);
                bizUserAccount.setGiveAwayAmount(bizUserAccount.getGiveAwayAmount().subtract(subGiveAwayAmount));
            }
            bizUserAccount.setConsumeAmount(bizUserAccount.getConsumeAmount().add(orderAmount));
            bizUserAccount.updateById();
            //更新用户的陪护豆余额
            user.setEscortBeanCount(bizUserAccount.getAccountBalance().add(bizUserAccount.getGiveAwayAmount()).add(bizUserAccount.getCommissionAmount()));
            sysUserMapper.updateUser(user);
            loginUser.setUser(user);
            tokenService.refreshToken(loginUser);
            //记录交易记录
            bizUserTradeRecordService.saveUserTradeRecord(user.getUserId(), orderAmount.negate(), BizUserTradeTypeEnum.BUY_SERVICE.getCode(),
                    bizServiceOrder.getServiceOrderSn(), flag ? bizService.getName() : bizCombo.getComboName());
        }
        return update;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean logicDeleteOrder(Long id) {
        BizServiceOrder bizServiceOrder = BizServiceOrder.DAO.selectById(id);
        if (!(BizOrderStatusEnum.COMPLETED.getCode().equals(bizServiceOrder.getOrderStatus()) ||
                BizOrderStatusEnum.CANCELLED.getCode().equals(bizServiceOrder.getOrderStatus()))) {
            throw new ApiException("此订单状态不可进行删除");
        }
        bizServiceOrder.setDelFlag("1");
        bizServiceOrder.setUpdateTime(DateUtils.getNowDate());
        bizServiceOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        return bizServiceOrder.updateById();
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateServiceOrderStatus(Date dateTime) {
        try {
            //log.info("=====将【服务订单】更新为已取消【开始】====");
            Date nowDate = DateUtils.getNowDate();
            LambdaQueryWrapper<BizServiceOrder> wrapper = new LambdaQueryWrapper<BizServiceOrder>();
            wrapper.eq(BizServiceOrder::getOrderStatus, BizOrderStatusEnum.PENDING_PAY.getCode())
                    .le(BizServiceOrder::getPaymentExpireTime, dateTime);
            List<BizServiceOrder> orderList = BizServiceOrder.DAO.selectList(wrapper);
            for (BizServiceOrder bizOrder : orderList) {
                BizServiceOrder updateOrder = new BizServiceOrder();
                updateOrder.setOrderStatus(BizOrderStatusEnum.CANCELLED.getCode());
                updateOrder.setCancelTime(nowDate);
                updateOrder.setId(bizOrder.getId());
                updateOrder.setUpdateTime(DateUtils.getNowDate());
                updateOrder.setUpdateBy("admin");
                bizServiceOrderMapper.updateById(updateOrder);

            }
            //log.info("=====将【服务订单】更新为已取消【结束】====");
        } catch (Exception e) {
            //log.error("=====将【服务订单】更新为已取消【异常】====" + e.getMessage());
        }
    }



    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateServiceOrderAcceptStatus(Date dateTime) {
        try {
            //log.info("=====将【服务订单】指派到随机客服====");
        LambdaQueryWrapper<BizServiceOrder> wrapper = new LambdaQueryWrapper<BizServiceOrder>();
            wrapper.eq(BizServiceOrder::getOrderStatus, BizOrderStatusEnum.PENDING_ORDER.getCode())
                    .le(BizServiceOrder::getAcceptExpireTime, dateTime);
            List<BizServiceOrder> orderList = BizServiceOrder.DAO.selectList(wrapper);
            List<AppKfUserVO> userVOList =  bizMessageConversationMapper.selectAllKfUser();
            AppKfUserVO appKfUserVO = userVOList.get(new Random().nextInt(userVOList.size()));
            for (BizServiceOrder bizOrder : orderList) {
                BizServiceOrder updateOrder = new BizServiceOrder();
                updateOrder.setOrderStatus(BizOrderStatusEnum.PENDING_SERVICE.getCode());
                updateOrder.setKfId(appKfUserVO.getUserId());
                updateOrder.setAcceptUserId(null);
                updateOrder.setId(bizOrder.getId());
                updateOrder.setUpdateTime(DateUtils.getNowDate());
                updateOrder.setUpdateBy("admin");
                bizServiceOrderMapper.updateServiceOrderAcceptStatus(updateOrder);
            }
            //log.info("=====将【服务订单】更新为已取消【结束】====");
        } catch (Exception e) {
            //log.error("=====将【服务订单】更新为已取消【异常】====" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean receiveOrder(Long id) {
        BizServiceOrder serviceOrder = BizServiceOrder.DAO.selectById(id);
        if (StringUtils.isNull(serviceOrder)) {
            throw new ApiException("订单不存在");
        }
        if (!BizOrderStatusEnum.PENDING_ORDER.getCode().equals(serviceOrder.getOrderStatus())) {
            throw new ApiException("此订单状态不可进行接单");
        }
//        SysUser sysUser = sysUserMapper.selectUserById(serviceOrder.getAcceptUserId());
//        //接单了就变成订单人员待服务的状态
//        if(UserTypeEnum.DOCTOR.getCode().equals(sysUser.getUserType())){
//            serviceOrder.setOrderStatus(BizOrderStatusEnum.SERVING.getCode());
//        }else {
//            serviceOrder.setOrderStatus(BizOrderStatusEnum.PENDING_SERVICE.getCode());
//        }
        serviceOrder.setOrderStatus(BizOrderStatusEnum.SERVING.getCode());
        serviceOrder.setUpdateTime(DateUtils.getNowDate());
        serviceOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        return serviceOrder.updateById();
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean signInOrder(AppSignInOrderFormVO formVO) {
        //String signInDistance = sysConfigService.selectConfigByKey(ConfigConstants.SIGN_IN_DISTANCE);
        BizServiceOrder serviceOrder = BizServiceOrder.DAO.selectById(formVO.getId());
        if (StringUtils.isNull(serviceOrder)) {
            throw new ApiException("订单不存在");
        }
//        BizHospital hospital = BizHospital.DAO.selectById(serviceOrder.getHospitalId());
//        if (StringUtils.isNotNull(hospital)) {
//            if (StringUtils.isNotBlank(hospital.getLatitude()) && StringUtils.isNotBlank(hospital.getLongitude())) {
//                double distance = DistanceUtils.getDistance(Double.parseDouble(formVO.getCurrentLongitude()), Double.parseDouble(formVO.getCurrentLatitude()),
//                        Double.parseDouble(hospital.getLongitude()), Double.parseDouble(hospital.getLatitude()));
//                if (distance > Double.parseDouble(signInDistance)) {
//                    throw new ApiException("抱歉,您不在签到范围之内。请移动至距离医院" + signInDistance + "KM内进行签到");
//                }
//            }
//
//        }
        serviceOrder.setSignLatitude(formVO.getCurrentLatitude());
        serviceOrder.setSignLongitude(formVO.getCurrentLongitude());
        serviceOrder.setOrderStatus(BizOrderStatusEnum.SERVING.getCode());
        serviceOrder.setSignInTime(DateUtils.getNowDate());
        serviceOrder.setUpdateTime(DateUtils.getNowDate());
        serviceOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        return serviceOrder.updateById();
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean completeOrder(Long id) {
        BizServiceOrder serviceOrder = BizServiceOrder.DAO.selectById(id);
        if (StringUtils.isNull(serviceOrder)) {
            throw new ApiException("订单不存在");
        }
        /*  现在所有的订单结算等 不走平台 ，去在


        LambdaQueryWrapper<BizServiceOrderDataUpload> lambdaQueryWrapper = new LambdaQueryWrapper<BizServiceOrderDataUpload>()
                .eq(BizServiceOrderDataUpload::getServiceOrderId,id);
        List<BizServiceOrderDataUpload> dataUploadList = BizServiceOrderDataUpload.DAO.selectList(lambdaQueryWrapper);
        if(CollectionUtil.isEmpty(dataUploadList)){
            throw new ApiException("请至少上传一次订单资料信息");
        }*/
        serviceOrder.setOrderStatus(BizOrderStatusEnum.COMPLETED.getCode());
        serviceOrder.setFinishTime(DateUtils.getNowDate());
        serviceOrder.setUpdateTime(DateUtils.getNowDate());
        serviceOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        boolean update = serviceOrder.updateById();
        /*
        if(update){
            //将陪护赚的钱加到提现金额中
            LambdaQueryWrapper<BizUserAccount> queryWrapper = new LambdaQueryWrapper<BizUserAccount>()
                    .eq(BizUserAccount::getUserId,serviceOrder.getAcceptUserId());
            BizUserAccount bizUserAccount = BizUserAccount.DAO.selectOne(queryWrapper);
            if(StringUtils.isNotNull(bizUserAccount)){
                bizUserAccount.setCommissionAmount(bizUserAccount.getCommissionAmount().add(serviceOrder.getExpectIncomeAmount()));
                bizUserAccount.setUpdateTime(DateUtils.getNowDate());
                bizUserAccount.setUpdateBy(bizUserAccount.getCreateBy());
                bizUserAccountMapper.updateById(bizUserAccount);
            }

            SysUser sysUser = sysUserMapper.selectUserById(serviceOrder.getAcceptUserId());
            SysUser userEntity = new SysUser();
            userEntity.setUserId(serviceOrder.getAcceptUserId());
            userEntity.setEscortBeanCount(bizUserAccount.getAccountBalance().add(bizUserAccount.getGiveAwayAmount()).add(bizUserAccount.getCommissionAmount()));
            //完成服务后，累加计算接单人的陪诊数量
            userEntity.setRecordNum(sysUser.getRecordNum() + 1);
            sysUserMapper.updateUser(userEntity);
            //分佣记录
            BizUserCommission commission = new BizUserCommission();
            commission.setUserId(serviceOrder.getAcceptUserId());
            commission.setSource(BizUserCommission.TYPE_ORDER);
            commission.setRechargeId(serviceOrder.getId());
            commission.setRechargeUserId(serviceOrder.getUserId());
            commission.setRechargeAmount(serviceOrder.getAmount());
            commission.setCommissionLevel(1);
            commission.setCommissionAmount(serviceOrder.getExpectIncomeAmount());
            commission.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
            commission.setCreateTime(DateUtils.getNowDate());
            commission.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
            commission.setUpdateTime(DateUtils.getNowDate());
            bizUserCommissionMapper.insert(commission);

            //交易记录
            bizUserTradeRecordService.saveUserTradeRecord(serviceOrder.getAcceptUserId(),serviceOrder.getExpectIncomeAmount(),BizUserTradeTypeEnum.ORDER_COMMISSION.getCode(),
                                                         serviceOrder.getServiceOrderSn(),"服务订单收入(获得"+serviceOrder.getExpectIncomeAmount().setScale(0)+"陪护豆)");
        }*/
        return update;
    }


}
